#!/usr/bin/env python
# coding: utf-8

# In[7]:


#画出驾驶行为识别结果
import urllib
import base64
import json

client_id ="	MQ4MVPdXYvgthZs4ywQGoIQS"
client_secret ="YtgDF4n5qLtNfKyYNLFKW5IAhqz52tSc"
 
#获取token
def get_token():
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + client_id + '&client_secret=' + client_secret
    request = urllib.request.Request(host)
    request.add_header('Content-Type', 'application/json; charset=UTF-8')
    response = urllib.request.urlopen(request)
    token_content = response.read()
    #print (token_content)
    if token_content:
        token_info = json.loads(token_content)
        token_key = token_info['access_token']
    return token_key



def driver_result(originfilename,persons,resultfilename,fontsize,fontcolor):
    from PIL import Image, ImageDraw,ImageFont
 
    image_origin = Image.open(originfilename)
    draw =ImageDraw.Draw(image_origin)
    setFont = ImageFont.truetype('C:/windows/fonts/simfang.ttf', fontsize)
    for person in persons:
        warning=''
        result=''
        attributes=person['attributes']
        #使用手机
        score = attributes['cellphone']['score']
        threshold = attributes['cellphone']['threshold']
        if score>threshold:
            warning=warning+'使用手机 '
        result=result+('使用手机： {:.5f} \n'.format(score))
        #抽烟
        score = attributes['smoke']['score']
        threshold = attributes['smoke']['threshold']
        if score>threshold:
            warning=warning+'抽烟 '
        result=result+( '抽烟： {:.5f} \n'.format(score))
        #未系安全带
        score = attributes['not_buckling_up']['score']
        threshold = attributes['not_buckling_up']['threshold']
        if score>threshold:
            warning=warning+'未系安全带 '
        result=result+( '未系安全带： {:.5f} \n'.format(score))
        #双手离开方向盘
        score = attributes['both_hands_leaving_wheel']['score']
        threshold = attributes['both_hands_leaving_wheel']['threshold']
        if score>threshold:
            warning=warning+'双手离开方向盘 '
        result=result+( '双手离开方向盘： {:.5f} \n'.format(score))
        #视角未看前方
        score = attributes['not_facing_front']['score']
        threshold = attributes['not_facing_front']['threshold']
        if score>threshold:
            warning=warning+'视角未看前方 '
        result=result+( '视角未看前方： {:.5f} \n'.format(score))
        
        gesture = person['location'] 
        draw.rectangle((gesture['left'],gesture['top'],gesture['left']+gesture['width'],gesture['top']+gesture['height']),outline = "red")
        
        if warning=='':
            warning='无'
        result=result+ '需要警告内容：'+warning
        print(result)
        draw.text((gesture['left'],gesture['top']), result,font=setFont,fill=fontcolor)
        
    image_origin.save(resultfilename, "JPEG")
      
#驾驶行为识别
#filename:原图片名（本地存储包括路径）
def driver_behavior(filename,resultfilename,fontsize,color):
    request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/driver_behavior"
    print(filename)
    # 二进制方式打开图片文件
    f = open("sj.jpg", 'rb')
    img = base64.b64encode(f.read())
    
    params = dict()
    params['image'] = img
    params = urllib.parse.urlencode(params).encode("utf-8")
    #params = json.dumps(params).encode('utf-8')
    
    access_token = "MQ4MVPdXYvgthZs4ywQGoIQS"
#     begin = time.perf_counter()
    request_url = request_url + "?access_token=" + access_token
    request = urllib.request.Request(url=request_url, data=params)
    request.add_header('Content-Type', 'application/x-www-form-urlencoded')
    response = urllib.request.urlopen(request)
    content = response.read()
#     end = time.perf_counter()
 
#     print('处理时长:'+'%.2f'%(end-begin)+'秒')
    if content:
        #print(content)
        content=content.decode('utf-8')
        #print(content)
        data = json.loads(content)
        print('人数:',data['person_num'])
        #print(data)
        result=data['person_info']
        
        driver_result(filename,result,resultfilename,fontsize,color)
 
driver_behavior('sj.jpg','sj.jpg',20,'blue')


# In[6]:



# -*- coding: utf-8 -*-
#!/usr/bin/env python
 
import urllib
import base64
import json
import time
import json
#client_id 为官网获取的AK， client_secret 为官网获取的SK
client_id ="MQ4MVPdXYvgthZs4ywQGoIQS"
client_secret ="YtgDF4n5qLtNfKyYNLFKW5IAhqz52tSc"
 
#获取token
def get_token():
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + client_id + '&client_secret=' + client_secret
    request = urllib.request.Request(host)
    request.add_header('Content-Type', 'application/json; charset=UTF-8')
    response = urllib.request.urlopen(request)
    token_content = response.read()
    print (token_content)
    if token_content:
        token_info = json.loads(token_content)
        token_key = token_info['access_token']
    return token_key

def driver_result(originfilename,persons,resultfilename,fontsize,fontcolor):
    from PIL import Image, ImageDraw,ImageFont
 
    image_origin = Image.open(originfilename)
    draw =ImageDraw.Draw(image_origin)
    setFont = ImageFont.truetype('C:/windows/fonts/simfang.ttf', fontsize)
    for person in persons:
        warning=''
        result=''
        attributes=person['attributes']
        #使用手机
        score = attributes['cellphone']['score']
        threshold = attributes['cellphone']['threshold']
        if score>threshold:
            warning=warning+'使用手机 '
        result=result+('使用手机： {:.5f} \n'.format(score))
        #抽烟
        score = attributes['smoke']['score']
        threshold = attributes['smoke']['threshold']
        if score>threshold:
            warning=warning+'抽烟 '
        result=result+( '抽烟： {:.5f} \n'.format(score))
        #未系安全带
        score = attributes['not_buckling_up']['score']
        threshold = attributes['not_buckling_up']['threshold']
        if score>threshold:
            warning=warning+'未系安全带 '
        result=result+( '未系安全带： {:.5f} \n'.format(score))
        #双手离开方向盘
        score = attributes['both_hands_leaving_wheel']['score']
        threshold = attributes['both_hands_leaving_wheel']['threshold']
        if score>threshold:
            warning=warning+'双手离开方向盘 '
        result=result+( '双手离开方向盘： {:.5f} \n'.format(score))
        #视角未看前方
        score = attributes['not_facing_front']['score']
        threshold = attributes['not_facing_front']['threshold']
        if score>threshold:
            warning=warning+'视角未看前方 '
        result=result+( '视角未看前方： {:.5f} \n'.format(score))
        
        gesture = person['location'] 
        draw.rectangle((gesture['left'],gesture['top'],gesture['left']+gesture['width'],gesture['top']+gesture['height']),outline = "red")
        
        if warning=='':
            warning='无'
        result=result+ '需要警告内容：'+warning
        print(result)
        draw.text((gesture['left'],gesture['top']), result,font=setFont,fill=fontcolor)
        
    image_origin.save(resultfilename, "JPEG")
      
#驾驶行为识别
#filename:原图片名（本地存储包括路径）
def driver_behavior(filename,resultfilename,fontsize,color):
    request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/driver_behavior"
    print(filename)
    # 二进制方式打开图片文件
    f = open("sj.jpg", 'rb')
    img = base64.b64encode(f.read())
    
    params = dict()
    params['image'] = img
    params = urllib.parse.urlencode(params).encode("utf-8")
    params = json.dumps(params).encode('utf-8')
    
    access_token = "MQ4MVPdXYvgthZs4ywQGoIQS"
    begin = time.perf_counter()
    request_url = request_url + "?access_token=" + access_token
    request = urllib.request.Request(url=request_url, data=params)
    request.add_header('Content-Type', 'application/x-www-form-urlencoded')
    response = urllib.request.urlopen(request)
    content = response.read()
    end = time.perf_counter()
 
    print('处理时长:'+'%.2f'%(end-begin)+'秒')
    
    if content:
        print(content)
        content=content.decode('utf-8')
        print(content)
        data = json.loads(content)
        print('人数:',data['person_num'])
        print(data)
        result=data['person_info']
        
        driver_result(filename,result,resultfilename,fontsize,color)
 
driver_behavior('sj.jpg','sj.jpg',20,'blue')


# In[ ]:




